package ru.nlezhnev.utils;

import java.util.Map;

import org.lorecraft.phparser.SerializedPhpParser;

import flex.messaging.io.amf.ASObject;

public class PhpDecoder {
	static public Object decode(String serializedPhp) {
		Object result = null;
		try {
			SerializedPhpParser serializedPhpParser = new SerializedPhpParser(serializedPhp, false);
			Map<?, ?> map = (Map<?, ?>)serializedPhpParser.parse();		
			result = convertValue(map);
		} catch (Exception e) {
			System.out.println("Invalid php serialized data");
		}		
		return result;
	}
	
	static private Object convertValue(Object sourceValue) {
		if (sourceValue instanceof Map) {
			Map<?, ?> sourceValueMap = (Map<?, ?>)sourceValue;  

			ASObject targetValue = new ASObject();
			if (sourceValueMap.get("_explicitType") != null) {
				targetValue.setType((String)sourceValueMap.get("_explicitType"));
				sourceValueMap.remove("_explicitType");
			}
			return convertMultipleValues((Map<?, ?>)sourceValue, targetValue);
		} else {
			return sourceValue;
		}
	}

	@SuppressWarnings("unchecked")
	static private Object convertMultipleValues(Map<?, ?> sourceMap, ASObject target) {
		for (Object key : sourceMap.keySet()) {
			Object sourceValue = sourceMap.get(key);
			target.put(key, convertValue(sourceValue));
		}
		return target;
	}
}
